import { useState } from "react";
import SeatList from "../../../components/SeatList";
import { sendData } from "../../../utils/websocket";
import { Upload, message, Button } from "antd";
import { UploadOutlined } from "@ant-design/icons";
import * as React from 'react';
import InputLabel from '@mui/material/InputLabel';
import MenuItem from '@mui/material/MenuItem';
import FormControl from '@mui/material/FormControl';
import Select from '@mui/material/Select';
import Box from '@mui/material/Box';
import Divider from '@mui/material/Divider';
import IdLabel from "../../../components/IdLabel";
const WaitingRoom = (props) => {
  const { room, seat, ...otherProps } = props;
  const [disabled, setDisabled] = useState(false);
  const isPlayer = !!seat;
  const isCreator = isPlayer && room.players[seat]?.is_creator;
  const [fileContent, setFileContent] = useState('')

  const [selectedRule, setSelectedRule] = React.useState('');
  const [selectedStrategy, setSelectedStrategy] = React.useState('');

  const handleChange = (event) => {
    setSelectedRule(event.target.value);
  };
  const handleChange2 = (event) => {
    setSelectedStrategy(event.target.value);
  };
  const uploadConfig = {
    name: "rule",
    accept: ".txt",
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    onChange(info) {
      if (info.file.status === "done") {
        message.success(`${info.file.name} 文件上传成功`);
        sendData("user.upload.file", {
          path: room.id,
          fileName: info.file.name,
          content: fileContent,
          fileType: "rule"
        })
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 文件上传失败.`);
      }
    },
    beforeUpload(file) {
      let reader = new FileReader();
      reader.readAsText(file);
      reader.onload = (ev) => {
        setFileContent(ev.target.result)
      }
    }
  };
  const uploadConfig2 = {
    name: "rule",
    accept: ".py",
    action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
    onChange(info) {
      if (info.file.status === "done") {
        message.success(`${info.file.name} 文件上传成功`);
        sendData("user.upload.file", {
          path: room.id,
          fileName: info.file.name,
          content: fileContent,
          fileType: "python"
        })
      } else if (info.file.status === "error") {
        message.error(`${info.file.name} 文件上传失败.`);
      }
    },
    beforeUpload(file) {
      let reader = new FileReader();
      reader.readAsText(file);
      reader.onload = (ev) => {
        setFileContent(ev.target.result)
      }
    }
  };
  return (
    <div {...otherProps}>
      <IdLabel />
      <h1>房间号：{room.id}</h1>
      {!isPlayer && <h1>您正在观战，请等待房主开局</h1>}
      <SeatList
        seat={seat}
        players={room.players}
        onClickSeat={(seat) => {
          if (room.players[seat] === null)
            sendData("user.seat.change", { seat });
        }}
      />
      <Divider />
      <Box
        sx={{
          display: "flex",
          justifyContent: "center",
          flexDirection: "row",
        }}
      >
        {isCreator && (
          <>
            <Box
              sx={{
                marginTop: "30px",
                marginRight: "100px",
                width: 300,
                height: 300,
                borderRadius: "20px",
                border: "1px solid skyblue",
                display: "flex",
                flexDirection: "column",
                justifyContent: "space-around",
                alignItems: "center"
              }}
            >
              <FormControl sx={{ m: 1, minWidth: 240 }}>
                <InputLabel id="demo-controlled-open-select-label">规则</InputLabel>
                <Select
                  labelId="demo-controlled-open-select-label"
                  id="demo-controlled-open-select"
                  value={selectedRule}
                  label="Rule"
                  onChange={handleChange}
                >
                  {room.rules?.map((item) => {
                    return <MenuItem value={item.path}>{item.name}</MenuItem>
                  })}
                </Select>
              </FormControl>
              <Upload {...uploadConfig} >
                <Button
                  icon={<UploadOutlined />}
                >
                  上传规则文件
                </Button>
              </Upload>
            </Box>
            <Box
              sx={{
                marginTop: "30px",
                marginLeft: "100px",
                width: 300,
                height: 300,
                borderRadius: "20px",
                border: "1px solid skyblue",
                display: "flex",
                flexDirection: "column",
                justifyContent: "space-around",
                alignItems: "center"
              }}
            >
              <FormControl sx={{ m: 1, minWidth: 240 }}>
                <InputLabel id="demo-controlled-open-select-label2">策略</InputLabel>
                <Select
                  labelId="demo-controlled-open-select-label2"
                  id="demo-controlled-open-select2"
                  value={selectedStrategy}
                  label="Strategy"
                  onChange={handleChange2}
                >
                  {room.strategies?.map((item) => {
                    return <MenuItem value={item.path}>{item.name}</MenuItem>
                  })}
                </Select>
              </FormControl>
              <Upload {...uploadConfig2} >
                <Button
                  icon={<UploadOutlined />}
                >
                  上传策略文件
                </Button>
              </Upload>
            </Box>
          </>
        )

        }

        {
          !isCreator && isPlayer && (
            <>
              <Box
                sx={{
                  marginTop: "30px",
                  width: 300,
                  height: 300,
                  borderRadius: "20px",
                  border: "1px solid skyblue",
                  display: "flex",
                  flexDirection: "column",
                  justifyContent: "space-around",
                  alignItems: "center"
                }}
              >
                <FormControl sx={{ m: 1, minWidth: 240 }}>
                  <InputLabel id="demo-controlled-open-select-label2">策略</InputLabel>
                  <Select
                    labelId="demo-controlled-open-select-label2"
                    id="demo-controlled-open-select2"
                    value={selectedStrategy}
                    label="Strategy"
                    onChange={handleChange2}
                  >
                    {room.strategies?.map((item) => {
                      return <MenuItem value={item.path}>{item.name}</MenuItem>
                    })}
                  </Select>
                </FormControl>
                <Upload {...uploadConfig2} >
                  <Button
                    icon={<UploadOutlined />}
                  >
                    上传策略文件
                  </Button>
                </Upload>
              </Box>
            </>
          )
        }
      </Box>
      {
        isCreator ? (
          <Box sx={
            { display: 'flex', justifyContent: "center", marginTop: "50px" }
          }>
            <Button
              disabled={room.players.includes(null, 1) || disabled}
              onClick={() => {
                setDisabled(true);
                sendData(
                  "user.test.game",
                  { selectedStrategy, selectedRule },
                  (data) => !data.ok && setDisabled(false)
                );
                console.log(selectedRule, selectedStrategy);
              }}
            >
              开始游戏
            </Button>
          </Box>

        ) : (
          <Box sx={
            { display: 'flex', justifyContent: "center", marginTop: "50px" }
          }>
            <Button
              onClick={() => {
                sendData(
                  "user.prepare.game",
                  { selectedStrategy },
                );
                console.log(selectedStrategy);
              }}
            >
              准备
            </Button>
          </Box>
        )
      }
      {/* <Button
        onClick={() => {
          sendData(
            "user.test.game",
            { selectedStrategy, selectedRule },
          );
          console.log(selectedRule, selectedStrategy);
        }}
      >
        test
      </Button> */}
    </div >
  );
};

export default WaitingRoom;
